"""
Grave! Important! Важно!

Proletoj el ĉiuj landoj, unuiĝu!
Workers of the world, unite!
Пролетарии всех стран, соединяйтесь!

https://tkom.pro
"""

from rest_framework import generics, views, authentication, permissions
from rest_framework.response import Response
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import redirect, reverse
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import requires_csrf_token, csrf_protect
from django.utils.translation import ugettext as _
from django.middleware.csrf import rotate_token
from main.models import Uzanto
import re


@method_decorator(csrf_protect, name='dispatch')
class EnsalutiView(views.APIView):
    permission_classes = (permissions.AllowAny,)
    http_method_names = ['get', 'post']

    def get(self, request, **kwargs):
        if request.user.is_authenticated:
            response = {'detail': _("Вы уже авторизированы")}
        else:
            rotate_token(request)
            response = {
                'detail': _("Для авторизации требуется обратиться по этому адресу методом POST"),
            }

        return Response(response)

    def post(self, request, **kwargs):
        response = {'status': 'error', 'detail': _("Ошибка аутентификации")}

        if 'username' in request.data and 'password' in request.data:
            uzanto = authenticate(username=request.data.get('username').lower(), password=request.data.get('password'))

            if uzanto is not None:
                if uzanto.is_authenticated:
                    response['detail'] = _("Вы уже авторизированы")
                if not uzanto.is_active:
                    response['detail'] = _("Учетная запись пользователя блокирована")
                elif not uzanto.konfirmita:
                    response['detail'] = _("Учетная запись ещё не активирована")
                else:
                    login(request, uzanto)

                    if 'after_login' in request.session:
                        url = request.session['after_login']
                        del (request.session['after_login'])
                        return redirect(url, permanent=True)
                    elif 'HTTP_REFERER' in request.META \
                            and re.search('%s$' % (reverse('api:ensaluti')),
                                          request.META['HTTP_REFERER']) is None:
                        return redirect(request.META['HTTP_REFERER'], permanent=True)
                    return redirect('start_page', permanent=True)
            else:
                response['detail'] = _("Неверный логин или пароль")

        else:
            response['detail'] = _('Запрос должен содержать поля "username" и "password"')

        return Response(response)


class ElsalutiView(views.APIView):
    permission_classes = (permissions.IsAuthenticated,)
    http_method_names = ['get']

    def get(self, request, **kwargs):
        if isinstance(request.user, Uzanto):
            logout(request)

        if 'HTTP_REFERER' in request.META \
                and re.search('%s$' % (reverse('api:elsaluti')),
                              request.META['HTTP_REFERER']) is None:
            return redirect(request.META['HTTP_REFERER'])
        return redirect('start_page')
